/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.pays;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.DiscountType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.entity.enums.UseScene;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;
import com.qinyeit.serviceapp.service.members.MemberCardTypeService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.pays.DiscountBranchService;
import com.qinyeit.serviceapp.service.pays.DiscountDetailService;
import com.qinyeit.serviceapp.service.pays.DiscountPlanService;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: DiscountPlansController <br/>
 * Function: discountPlan [折扣方案] <br/>
 * date: 2018-11-29 09:56:09 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/pays/discountPlans")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_discountPlan:read",name ="折扣方案",deleteAble = false)
public class DiscountPlansController extends BaseManagementController{

	@Autowired
	private DiscountPlanService discountPlanService;
	@Autowired
	private DishesStoreService dishesStoreService;
	@Autowired
	private DiscountDetailService discountDetailService;
	@Autowired
	private DiscountBranchService discountBranchService;
	@Autowired
	private BranchService branchService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private MemberCardTypeService memberCardTypeService;

	private final String [] keys = {"id","type","name","hasVip","storeId","startTime","endTime","discount","operatorName","operateTime","state","branchs","useScene","specialDiscount"};

    @RequiresPermissions("management_discountPlan:show")
    @PermissionInfo(code = "management_discountPlan:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<DiscountPlan> discountPlanPage = discountPlanService.findAll(searchable);
        if(CollectionUtils.isNotEmpty(discountPlanPage.getContent())){
            List<DiscountBranch> branchList = null;
            searchable = SearchableUtils.newSearchableWithMerchantFilter();
            for (DiscountPlan plan : discountPlanPage.getContent()) {
                searchable.addSearchParam("discountId_eq",plan.getId());
                branchList = discountBranchService.findWithSort(searchable);
                if(CollectionUtils.isNotEmpty(branchList)){
                    plan.setBranchs(branchList.size()+"");
                }
            }
        }
        return ok("查询成功", JSONUtils.include(discountPlanPage,new Class[]{DiscountType.class,State.class,UseScene.class}, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("discountPlan",JSONUtils.include(new DiscountPlan(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_discountPlan:create")
    @PermissionInfo(code = "management_discountPlan:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject discountPlan, BindingResult bindingResult){
//        if(discountPlanService.exists(buildExists(null, "no", discountPlan.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        discountPlanService.saveData(discountPlan, CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute DiscountPlan discountPlan){
        return ok("查询成功", JSONUtils.include(discountPlan, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute DiscountPlan discountPlan){
        QyMap map=QyMap.NEW();
        map.setv("discountPlan",JSONUtils.include(discountPlan, keys));
        initFormDate(map);
        //折扣明细
        if(discountPlan.getType()==DiscountType.PLAN){
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("discountId_eq",discountPlan.getId());
            List<DiscountDetail> detailList = discountDetailService.findWithSort(searchable);
            map.setv("detailList",JSONUtils.include(detailList,"categoryId","dishesId","rate","specialRate"));
        }
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_discountPlan:update")
    @PermissionInfo(code = "management_discountPlan:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject discountPlan,BindingResult bindingResult){
//        if(discountPlanService.exists(buildExists(null, "no", discountPlan.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        discountPlanService.saveData(discountPlan,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_discountPlan:destory")
    @PermissionInfo(code = "management_discountPlan:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        //判断折扣方案是否在会员卡中使用 使用过 不允许删除
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("discountId_eq",id);
        Long count = memberCardTypeService.count(searchable);
        if(count.intValue()>0){
            return fail("已使用，不允许删除");
        }

        DiscountPlan plan = discountPlanService.findById(id);
        //判断门店的折扣方式是否被使用
        count = discountPlanService.branchUseCountForDiscountPlan(plan);
        if(count.intValue()>0){
            return fail("已使用,不允许删除");
        }
        plan.setUpdateTimestamp(DateUtils.current());
        discountPlanService.update(plan);
        discountPlanService.logicDelete(id);
        //删除分店的数据
        discountPlanService.deleteBranchDiscountPlanData(plan);
        return ok("删除成功", null);
    }



    /**
     * 分配门店 初始化
     * @param id
     * @return
     */
    @GetMapping("/allocationBranch")
    public ResponseResult<String> allocationBranch(Long id){
        QyMap map = QyMap.NEW();
        //区域门店
        map.setv("districts",getDistricts());
        if (id!=null){
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("discountId_eq",id);
            List<DiscountBranch> branchList = discountBranchService.findWithSort(searchable);
            Branch branchEn = null;
            if(CollectionUtils.isNotEmpty(branchList)){
                for (DiscountBranch branch : branchList) {
                    branchEn = branchService.findById(branch.getBranchId());
                    branch.setLabel(branchEn.getName());
                }
            }
            map.setv("branchList",JSONUtils.include(branchList,"branchId","districtId","label"));
        }
        return ok("查询成功", map);
    }


    /**
     * 分配门店 保存 (可批量分配机构)
     * @param data
     * @return
     */
    @RequiresPermissions("management_discountPlan:allocationBranch")
    @PermissionInfo(code = "management_discountPlan:allocationBranch",name ="分配门店",deleteAble = false)
    @PostMapping("/allocationBranch")
    public ResponseResult<String> allocationBranchSave(@RequestBody JSONObject data){
        discountPlanService.allocationBranchSave(data);
        return ok("保存成功");
    }

    /**
     * 查看所有门店
     *
     * @param id
     * @return
     */
    @GetMapping("/showAllBranchs")
    public ResponseResult<String> showAllBranchs(Long id){
        DiscountPlan discountPlan = discountPlanService.findById(id);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("discountId_eq",discountPlan.getId());
        List<DiscountBranch> branchList = discountBranchService.findWithSort(searchable);
        Branch branch = null;
        if(CollectionUtils.isNotEmpty(branchList)){
            for (DiscountBranch discountBranch : branchList) {
                branch = branchService.findById(discountBranch.getBranchId());
                discountBranch.setLabel(branch.getName());
            }
        }
        return ok("操作成功", JSONUtils.include(branchList,"id","branchId","districtId","label"));
    }


    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            DiscountPlan discountPlan = discountPlanService.findById(Long.valueOf(id));
            model.addAttribute(discountPlan);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
       //菜品库
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        List<DishesStore> storeList = dishesStoreService.findWithSort(searchable);
        qyMap.setv("storeList",JSONUtils.include(storeList,"id","name","state"));
        //折扣类型
        qyMap.setv("discountTypes", DiscountType.values());
        qyMap.setv("useScenes", UseScene.values());
    }

}